<?php

namespace App\Service\OpenShop\Feishu;

use App\Enums\BaseErrorCode;
use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Enums\OpenShop\InvestmentPromotion\ShopManualEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserBaseInfoEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\SignSiteMissionEvent;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Resources\OpenShop\ShopLocation\PlaceHolderSiteLocationResource;
use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use App\Models\College\CollegeTrainingOrderModel;
use App\Models\College\CollegeTrainingPlanModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrderTagsMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopShopManual;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftOutfitMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\ShopEngineeringConstruction\OpenShopEngineeringConstructionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationCustomerAnalysisModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationHouseEvaluateModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationProductAnalysisModel;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\OpenShop\FeishuMini\ConsultantsService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\SiteLocation\PlaceHolderSiteLocationService;
use App\Service\OpenShop\SiteLocation\SiteLocationAuditService;
use App\Service\OpenShop\SiteLocation\SiteLocationService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Rms\ShopService;
use App\Support\ChangeSupport;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Kuafu\File\FileUtil;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ShopTagsService extends BaseService
{
    private string $orderNo;
    private int    $shopId;
    private        $orderInfo;
    private array  $tags;

    public function __construct(string $orderNo, int $shopId = 0)
    {
        $this->orderNo = $orderNo;
        $this->shopId  = $shopId;

        if ($this->shopId && !$orderNo) {
            $mainProcess     = OpenShopMainProcessModel::query()->where('shopId', $shopId)->first();

            $this->orderInfo = $mainProcess->signOrderRel;
        } else {
            $this->orderInfo = OpenShopSignOrderModel::query()
                                      ->where('orderNo', $orderNo)
                                      ->with(['tagsMappingRel', 'progressRel'])
                                      ->first();
        }

        $this->tags = $this->orderInfo->tagsMappingRel->pluck('tagId')->toArray();
    }

    /**
     * 更新筹备正常, 异常 标签
     *
     * @return $this
     */
    public function updateOrderPrepareTag(): ShopTagsService
    {
        // 筹备标签初始化
        $hasCbTags = OpenShopOrderTagsMappingModel::checkTags($this->tags,
            OpenShopOrderTagsMappingModel::TAG_LIST_PREPARE);
        if (!$hasCbTags && $this->orderInfo->progressRel) {
            // 校验是否有筹备标签
            $tagPrepare = OpenShopOrderTagsMappingModel::getInfoByOrderNo($this->orderInfo->orderNo,
                OpenShopOrderTagsMappingModel::TAG_LIST_PREPARE);

            if (!$tagPrepare) {
                OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
                    OpenShopOrderTagsMappingModel::TAG_TYPE_1);
            }
        }

        $this->updateShopCancellation();
        return $this;
    }

    /**
     * 更新筹备正常, 异常 标签
     *
     * @return $this
     */
    public function updateShopCancellation(): ShopTagsService
    {
        // 筹备标签初始化
        $hasCbTags = OpenShopOrderTagsMappingModel::checkTags($this->tags,
            OpenShopOrderTagsMappingModel::TAG_LIST_CANCEL_STATUS);
        if (!$hasCbTags && $this->orderInfo->progressRel) {
            // 校验是否有筹备标签
            $tagPrepare = OpenShopOrderTagsMappingModel::getInfoByOrderNo($this->orderInfo->orderNo,
                OpenShopOrderTagsMappingModel::TAG_LIST_CANCEL_STATUS);

            if (!$tagPrepare) {
                OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
                    OpenShopOrderTagsMappingModel::TAG_TYPE_14);
            }
        }
        return $this;
    }

    /**
     * 更新 设计模块
     *
     * @return $this
     */
    public function updateDesignPayTag(): ShopTagsService
    {
        // 设计待支付更新状态


        // 加载关联模型
        $this->orderInfo->loadMissing([
            'spaceDesignCostRel' => function ($query
            ) {
                // 其余待支付的设计单
                $query->where('payStatus', '<',
                    OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_2)
                      ->where('orderStatus', '!=',
                          OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_3);
            }
        ]);

        if ($this->orderInfo->spaceDesignCostRel->count() > 0) {
            $hasTags = OpenShopOrderTagsMappingModel::checkTags($this->tags,
                OpenShopOrderTagsMappingModel::TAG_LIST_DESIGN);
            if (!$hasTags) {
                // 添加标签
                OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
                    OpenShopOrderTagsMappingModel::TAG_TYPE_3);
            }
        } else {
            // 删除标签
            OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo,
                OpenShopOrderTagsMappingModel::TAG_LIST_DESIGN);
        }
        return $this;
    }

    /**
     * 更新 设备的支付, 发货状态
     *
     * @return $this
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    public function updateKfosTag(): ShopTagsService
    {
        if (empty($this->orderInfo->progressRel->shopId)) {
            return $this;
        }
        $body = OrmNewOrderRemote::equipmentDeliveryNotes($this->orderInfo->progressRel->shopId,
            '2099-12-31');

        $unPayTag = false;
        if (isset($body['data']['orders'])) {
            foreach ($body['data']['orders'] as $datum) {
                if ($datum['paymentStatus'] == 1 && $datum['status'] != KfosService::NEW_ORDER_STATUS_CLOSED) {
                    $unPayTag = true;
                    break;
                }
            }
        }

        $tags = [];
        /*if (isset($body['data']['orders'])) {
            foreach ($body['data']['orders'] as $orders) {
                if ($orders['paymentStatus'] != 2 || $datum['status'] == KfosService::NEW_ORDER_STATUS_CLOSED) {
                    continue;
                }

                $newOrderGoods = collect($orders['newOrderGoods']);

                $numSum         = $newOrderGoods->sum('num');
                $deliveryNumSum = $newOrderGoods->sum('deliveryNum');

                if ($deliveryNumSum == 0) {
                    $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_5;
                } elseif ($deliveryNumSum < $numSum) {
                    $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_6;
                } elseif ($deliveryNumSum == $numSum) {
                    $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_7;
                }

            }
        }*/

        // 判断统配出库单物流信息
        $totalNum = $deliveryLogisticsSum = 0;
        if (isset($body['data']['list'])) {
            foreach ($body['data']['list'] as $v) {
                $totalNum++;
                if (isset($v['deliveryLogistics']) && count($v['deliveryLogistics']) > 0) {
                    $deliveryLogisticsSum++;
                }
            }
        }

        if ($deliveryLogisticsSum == 0) {
            $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_5;
        } elseif ($deliveryLogisticsSum < $totalNum) {
            $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_6;
        } elseif ($deliveryLogisticsSum == $totalNum) {
            $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_7;
        }

        $tags = array_unique($tags);

        // 删除所有支付标签
        OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_LIST_EQUIPMENT_PAY);
        if ($unPayTag) {
            OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
                OpenShopOrderTagsMappingModel::TAG_TYPE_4);
        }

        // 删除所有的设备发货状态
        OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_LIST_EQUIPMENT_DELIVER);

        foreach ($tags as $tag) {
            OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo, $tag);
        }

        return $this;
    }

    /**
     * 更新软装支付
     *
     * @return $this
     */
    public function updateSoftPayTag(): ShopTagsService
    {
        // 加载关联模型
        $this->orderInfo->loadMissing([
            'spaceDesignSoftOutfitRel' => function ($query
            ) {
                $query->where('orderStatus', '!=',
                    OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_STATUS_3);
            }
        ]);

        // 软装支付
        OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_LIST_SOFT_PAY);

        $count = $this->orderInfo->spaceDesignSoftOutfitRel->where('payStatus', '<',
            OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_PAY_STATUS_2)
                                                           ->count();

        if ($count > 0) {
            OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
                OpenShopOrderTagsMappingModel::TAG_TYPE_8);
        }

        $this->updateSoftPayDelivery();
        return $this;
    }

    /**
     * 软装发货状态
     *
     * @return $this
     */
    public function updateSoftPayDelivery(): ShopTagsService
    {
        $tags = [];

        // 软装待发货
        OpenShopOrderTagsMappingModel::delTags($this->orderNo,
            OpenShopOrderTagsMappingModel::TAG_LIST_SOFT_DELIVER);
//
//        $list = $this->orderInfo->spaceDesignSoftOutfitRel
//            ->where('payStatus',
//                OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_PAY_STATUS_2)
//            ->whereIn('orderStatus',
//                [
//                    OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_STATUS_0,
//                    OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_STATUS_1,
//                ]);
//
//        $tags = [];
//        $list->each(function ($item) use (&$tags) {
//            $count = $item->softLogisticsRel->count();
//            if ($count) {
//                $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_11;
//            } else {
//                $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_9;
//            }
//        });

        $lists = KfosService::equipmentDeliveryNotes($this->orderNo, CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE);

        // 待发货的订单数量
        $waitDeliveryNum = collect($lists['list'])
            ->where('status', KfosService::DELIVERY_NOTE_STATUS_CONFIRMED)->count();
        if ($waitDeliveryNum > 0) {
            $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_9;
        }

        // 已发货数量
        $finishDeliveryNum = collect($lists['list'])
            ->whereIn('status', [KfosService::DELIVERY_NOTE_STATUS_DELIVERED, KfosService::DELIVERY_NOTE_STATUS_RECEIVED, KfosService::DELIVERY_NOTE_STATUS_FINISHED])->count();

        // 全部发货了
        if ($finishDeliveryNum > 0 && $waitDeliveryNum == 0) {
            $tags[] = OpenShopOrderTagsMappingModel::TAG_TYPE_11;
        }

        $tags = array_unique($tags);
        foreach ($tags as $tag) {
            OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo, $tag);
        }

        return $this;
    }

    /**
     * 更新商学院的状态
     *
     * @return $this
     */
    public function updateSchoolTag(): ShopTagsService
    {
        if (empty($this->orderInfo->progressRel->shopId)) {
            return $this;
        }
        $collegeOrder = collegeTrainingOrderModel::query()
                                                 ->where('studentShopId',
                                                     $this->orderInfo->progressRel->shopId)
                                                 ->first();
        OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_LIST_SCHOOL);

        if (!$collegeOrder) {
            return $this;
        }

        in_array($collegeOrder->status, [
            collegeTrainingOrderModel::STATUS_ING,
            collegeTrainingOrderModel::STATUS_WAIT_UPLOAD,
            collegeTrainingOrderModel::STATUS_FINISH,
            collegeTrainingOrderModel::STATUS_CLOSE,
        ]) and OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_TYPE_13);

        in_array($collegeOrder->status, [
            collegeTrainingOrderModel::STATUS_MERCHANT_CONFIRM,
            collegeTrainingOrderModel::STATUS_COLLEGE_CONFIRM,
        ]) and OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_TYPE_12);

        return $this;
    }

    /**
     * 选址阶段，商家确认选址后自动移除选址阶段标记的「沉默客户」「待解约」标签。
     */
    public function removeTagsAfterMerchantAddress()
    {
        OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo,
            [
                OpenShopOrderTagsMappingModel::TAG_TYPE_16,
                OpenShopOrderTagsMappingModel::TAG_TYPE_15,
                OpenShopOrderTagsMappingModel::TAG_TYPE_14,
                OpenShopOrderTagsMappingModel::TAG_TYPE_17,
                OpenShopOrderTagsMappingModel::TAG_TYPE_18,
            ]);

        OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_TYPE_14);
    }


    /**
     * 筹备阶段，门店开业后自动移除筹备阶段标记的「筹备异常」「待解约」标签。
     */
    public function removeTagsAfterPrepareStartBusiness()
    {
        OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo,
            [
                OpenShopOrderTagsMappingModel::TAG_TYPE_2,
                OpenShopOrderTagsMappingModel::TAG_TYPE_15,
                OpenShopOrderTagsMappingModel::TAG_TYPE_14,
                OpenShopOrderTagsMappingModel::TAG_TYPE_1,
            ]);

        OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_TYPE_14);

        OpenShopOrderTagsMappingModel::addTags($this->orderInfo->orderNo,
            OpenShopOrderTagsMappingModel::TAG_TYPE_1);
    }

    /**
     * 工服待确认、待支付
     * @return void
     */
    public function updateWorkClothes()
    {
        $this->orderNo = $this->orderInfo->orderNo;
        if (!$this->shopId) {
            $this->shopId  = $this->orderInfo->progressRel->shopId;
        }

        OpenShopOrderTagsMappingModel::delTags($this->orderNo, OpenShopOrderTagsMappingModel::TAG_LIST_WORK_CLOTH);

        // 校区培训
        $planBuilders = CollegeTrainingPlanModel::query()
                                                ->where('type', CollegeTrainingPlanModel::TYPE_CAMPUS)
                                                ->select('id');

        $college = CollegeTrainingOrderModel::query()
                                            ->where('studentShopId', $this->shopId)
                                            ->whereRaw("planId in (" . BaseModel::toSqlWithParam($planBuilders) . ')')
                                            ->where('status', CollegeTrainingOrderModel::STATUS_ING,)
                                            ->first();

        if (!$college) {
            return;
        }


        $shopId     = KfosService::shopIdByOrderNo($this->orderNo);
        $orderLists = collect(OrmNewOrderRemote::equipmentDeliveryNotes($shopId, '2099-12-31', CheckEnum::SYS_TYPE_WORK_CLOTHES)['data']['orders']);

        // 检查是否有工服订单
        if (!$orderLists->where('status', '!=', OrmNewOrderRemote::NEW_ORDER_STATUS_CLOSE)->count()) {

            // 没有订货单
            OpenShopOrderTagsMappingModel::addTags($this->orderNo, OpenShopOrderTagsMappingModel::TAG_TYPE_19);
            return;
        }

        // 是否有待支付的工服订单
        if ($orderLists->whereIn('status',
            [OrmNewOrderRemote::NEW_ORDER_STATUS_WAIT, OrmNewOrderRemote::NEW_ORDER_STATUS_PART])
                       ->count()) {
            OpenShopOrderTagsMappingModel::addTags($this->orderNo, OpenShopOrderTagsMappingModel::TAG_TYPE_20);
            return;
        }
    }

    /**
     * 清除并添加标签
     *
     * @param array $addTags
     * @param array $dealTags
     */
    private function delAndAddTag(int $addTag, array $deleteTag)
    {
        OpenShopOrderTagsMappingModel::delTags($this->orderNo, $deleteTag);

        if ($addTag) {
            OpenShopOrderTagsMappingModel::addTags($this->orderNo, $addTag);
        }

    }


    /**
     * 删除商学院的状态
     *
     * @return $this
     */
    public function delSchoolTag(): ShopTagsService
    {
        if (empty($this->orderInfo->progressRel->shopId)) {
            return $this;
        }
        OpenShopOrderTagsMappingModel::delTags($this->orderInfo->orderNo, OpenShopOrderTagsMappingModel::TAG_LIST_SCHOOL);
        return $this;
    }
}
